package com.xmcc.service.impl;

import com.google.common.collect.Lists;
import com.xmcc.dao.*;
import com.xmcc.dto.SysRoleDto;
import com.xmcc.dto.SysRoleUserDto;
import com.xmcc.exception.ParamException;
import com.xmcc.pojo.*;
import com.xmcc.service.SysLogService;
import com.xmcc.service.SysRoleService;
import com.xmcc.utill.BeanValidator;
import com.xmcc.utill.IPUtils;
import com.xmcc.utill.ThreadLocalCommon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class SysRoleServiceImpl implements SysRoleService {
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleAclMapper sysRoleAclMapper;
    @Autowired
    private SysAclMapper sysAclMapper;

    @Autowired
    private SysLogService sysLogService;
    @Override
    public List<SysRole> selectAllRole() {
        return sysRoleMapper.selectAllRole();
    }

    //添加角色：
    @Override
    public void insert(SysRoleDto sysRoleDto) {
        //校验sysRoleDto传入的属性是否为空：
        BeanValidator.check(sysRoleDto);
        //校对角色名称是否存在：
        checkName(sysRoleDto.getName(),sysRoleDto.getId());
        SysRole sysRole = SysRole.builder().name(sysRoleDto.getName()).type(sysRoleDto.getType()).status(sysRoleDto.getStatus())
        .remark(sysRoleDto.getRemark()).build();

        sysRole.setOperator(ThreadLocalCommon.popSysUser().getUsername());
        sysRole.setOperateTime(new Date());
        sysRole.setOperateIp(IPUtils.getIpAddress(ThreadLocalCommon.popHttpServletRequest()));
        sysRoleMapper.insertSelective(sysRole);
    }

    //添加或者修改时校对角色名称是否存在：
    private void checkName(String name,Integer id) {
        if (sysRoleMapper.checkName(name,id)>0){
            throw new ParamException("该角色名称已存在!!");
        }
    }

    //修改角色：
    @Override
    public void update(SysRoleDto sysRoleDto) {
        //校验sysRoleDto传入的属性是否为空：
        BeanValidator.check(sysRoleDto);
        //校对角色名称是否存在：
        checkName(sysRoleDto.getName(),sysRoleDto.getId());
        SysRole sysRole = SysRole.builder().id(sysRoleDto.getId()).name(sysRoleDto.getName()).type(sysRoleDto.getType()).status(sysRoleDto.getStatus())
                .remark(sysRoleDto.getRemark()).build();

        sysRole.setOperator(ThreadLocalCommon.popSysUser().getUsername());
        sysRole.setOperateTime(new Date());
        sysRole.setOperateIp(IPUtils.getIpAddress(ThreadLocalCommon.popHttpServletRequest()));
        sysRoleMapper.updateByPrimaryKeySelective(sysRole);
    }

    //根据角色id查询到SysRoleUserDto对象：
    @Override
    public SysRoleUserDto usersList(Integer roleId) {
        SysRoleUserDto sysRoleUserDto = new SysRoleUserDto();
        List<SysRoleUser> sysRoleUsers = sysRoleUserMapper.roleUserList(roleId); //null
        System.out.println(sysRoleUsers);
        if (sysRoleUsers.size()!=0){
            sysRoleUserDto.setSelected(sysUserMapper.usersList(sysRoleUsers));
        }
        sysRoleUserDto.setUnselected(sysUserMapper.uNusersList(sysRoleUsers));
        return sysRoleUserDto;
    }


    //修改角色于权限的中间表数据：
    @Override
    public void changeAcls(Integer roleId, List<Integer> aclIds) {
        //通过角色id查询出之前拥有的权限
        //需要在删除之前查询
        List<Integer> oldAclIds = sysAclMapper.queryAclByRoleId2(roleId);

        //比较两个集合
        Set<Integer> oldAclSet = oldAclIds.stream().collect(Collectors.toSet());
        Set<Integer> newAclSet = aclIds.stream().collect(Collectors.toSet());
        boolean flag = false;
        for (Integer integer : oldAclSet) {
            if(!newAclSet.contains(integer)){
                flag=true;
                break;
            }
        }
        for (Integer integer : newAclSet) {
            if(!oldAclSet.contains(integer)){
                flag=true;
                break;
            }
        }
        if(!flag){
            return;
        }

       //记录
        sysLogService.saveRoleAcl(roleId,oldAclIds,aclIds);

        sysRoleAclMapper.deleteByPrimaryKeys(roleId);
        for (Integer aclId :aclIds) {
            SysRoleAcl sysRoleAcl = new SysRoleAcl();
            sysRoleAcl.setRoleId(roleId);
            sysRoleAcl.setAclId(aclId);
            //设置操作者信息：
            sysRoleAcl.setOperator(ThreadLocalCommon.popSysUser().getUsername());
            sysRoleAcl.setOperateTime(new Date());
            sysRoleAcl.setOperateIp(IPUtils.getIpAddress(ThreadLocalCommon.popHttpServletRequest()));
            //先清空roleId传过来的id，后添加数据：
            sysRoleAclMapper.insertSelective(sysRoleAcl);
        }
    }

    @Override
    public void changeUsers(Integer roleId, List<Integer> userIds) {


        sysRoleUserMapper.deleteByPrimaryKeys(roleId);
        for (Integer userId :userIds) {
            SysRoleUser sysRoleUser = new SysRoleUser();
            sysRoleUser.setRoleId(roleId);
            sysRoleUser.setUserId(userId);
            //设置操作者信息：
            sysRoleUser.setOperator(ThreadLocalCommon.popSysUser().getUsername());
            sysRoleUser.setOperateTime(new Date());
            sysRoleUser.setOperateIp(IPUtils.getIpAddress(ThreadLocalCommon.popHttpServletRequest()));
            //先清空roleId传过来的id，后添加数据：
            sysRoleUserMapper.insertSelective(sysRoleUser);
        }


    }

    @Override
    public void recover(SysLogWithBLOBs sysLogWithBLOBs) {

    }

}
